// 导入模板配置
import { templates } from './template-registry.js';

// 保存提取状态，按模板隔离
const extractionStates = new Map();
// 保存已注入的标签页
const injectedTabs = new Set();

// 获取或创建模板状态
function getTemplateState(templateId) {
  if (!extractionStates.has(templateId)) {
    extractionStates.set(templateId, {
      isRunning: false,
      templateId: templateId,
      result: null,
      error: null,
      merchantInfo: null
    });
  }
  return extractionStates.get(templateId);
}

// 注入content-script的通用函数
async function injectContentScript(tabId) {
  if (injectedTabs.has(tabId)) {
    console.log('Content script already injected for tab:', tabId);
    return;
  }
  
  try {
    await chrome.scripting.executeScript({
      target: { tabId: tabId },
      files: ['content-script.js']
    });
    injectedTabs.add(tabId);
    console.log('Content script injected for tab:', tabId);
  } catch (error) {
    console.error('Failed to inject content script:', error);
    throw error;
  }
}

// 监听标签页关闭，清理注入状态
chrome.tabs.onRemoved.addListener((tabId) => {
  injectedTabs.delete(tabId);
});

// 监听来自 popup 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'getTemplates') {
    // 返回模板配置
    sendResponse({ templates: templates });
    return true;
  } else if (request.action === 'getMerchantInfo') {
    // 获取当前标签页
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      const currentTab = tabs[0];
      
      // 注入内容脚本
      injectContentScript(currentTab.id).then(() => {
        // 然后发送消息给内容脚本获取商户信息
        chrome.tabs.sendMessage(
          currentTab.id,
          { action: 'getMerchantInfo' },
          function(response) {
            if (chrome.runtime.lastError) {
              sendResponse({ 
                success: false, 
                error: chrome.runtime.lastError.message 
              });
              return;
            }
            
            if (response && response.success) {
              // 保存商户信息到状态中
              const templateId = request.templateId;
              if (templateId) {
                const state = getTemplateState(templateId);
                state.merchantInfo = response.data;
              }
              
              sendResponse({ 
                success: true, 
                data: response.data 
              });
            } else {
              sendResponse({ 
                success: false, 
                error: response?.error || '未知错误' 
              });
            }
          }
        );
      }).catch(error => {
        sendResponse({ 
          success: false, 
          error: error.message 
        });
      });
    });
    return true; // 保持消息通道开放
  } else if (request.action === 'startExtraction') {
    const templateId = request.template;
    const state = getTemplateState(templateId);

    // 如果已经在运行，直接返回当前状态
    if (state.isRunning) {
      chrome.runtime.sendMessage({
        action: 'extractionStatus',
        state: state
      });
      return;
    }

    // 更新状态为运行中
    state.isRunning = true;
    state.result = null;
    state.error = null;

    // 获取当前标签页
    chrome.tabs.query({active: true, currentWindow: true}, async function(tabs) {
      const currentTab = tabs[0];
      
      try {
        // 注入内容脚本
        await injectContentScript(currentTab.id);

        // 先执行一次滚动
        await new Promise((resolve, reject) => {
          chrome.tabs.sendMessage(
            currentTab.id,
            { action: 'scrollContainer' },
            function(response) {
              if (chrome.runtime.lastError) {
                reject(new Error(chrome.runtime.lastError.message));
                return;
              }
              if (response && response.success) {
                resolve();
              } else {
                reject(new Error(response?.error || '滚动失败'));
              }
            }
          );
        });

        // 获取商户信息
        const merchantInfo = await new Promise((resolve, reject) => {
          chrome.tabs.sendMessage(
            currentTab.id,
            { action: 'getMerchantInfo' },
            function(response) {
              if (chrome.runtime.lastError) {
                reject(new Error(chrome.runtime.lastError.message));
                return;
              }
              if (response && response.success) {
                resolve(response.data);
              } else {
                reject(new Error(response?.error || '获取商户信息失败'));
              }
            }
          );
        });

        // 保存商户信息到状态中
        state.merchantInfo = merchantInfo;

        // 获取商户信息成功后，再开始提取数据
        chrome.tabs.sendMessage(
          currentTab.id,
          { 
            action: 'extract_metric', 
            templateId: templateId,
            scope: request.scope,
            autoExport: request.autoExport
          },
          function(response) {
            const currentState = getTemplateState(templateId);
            
            if (chrome.runtime.lastError) {
              currentState.isRunning = false;
              currentState.error = chrome.runtime.lastError.message;
              chrome.runtime.sendMessage({
                action: 'extractionComplete',
                state: currentState
              });
              return;
            }
            
            if (response && response.success) {
              currentState.isRunning = false;
              currentState.result = response.data;
              currentState.error = null;
              chrome.runtime.sendMessage({
                action: 'extractionComplete',
                state: currentState
              });
            } else {
              currentState.isRunning = false;
              currentState.result = null;
              currentState.error = response?.error || '未知错误';
              chrome.runtime.sendMessage({
                action: 'extractionComplete',
                state: currentState
              });
            }
          }
        );
      } catch (error) {
        const currentState = getTemplateState(templateId);
        currentState.isRunning = false;
        currentState.error = error.message;
        chrome.runtime.sendMessage({
          action: 'extractionComplete',
          state: currentState
        });
      }
    });
  } else if (request.action === 'stopExtraction') {
    const templateId = request.template;
    const state = getTemplateState(templateId);
    
    if (state.isRunning) {
      // 获取当前标签页
      chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        const currentTab = tabs[0];
        
        // 发送停止消息给内容脚本
        chrome.tabs.sendMessage(
          currentTab.id,
          { action: 'stop_extraction' }
        );
        
        // 更新状态
        state.isRunning = false;
        state.result = null;
        state.error = '用户停止提取';
        
        chrome.runtime.sendMessage({
          action: 'extractionComplete',
          state: state
        });
      });
    }
  } else if (request.action === 'getExtractionStatus') {
    const templateId = request.template;
    const state = getTemplateState(templateId);
    
    // 返回当前提取状态
    chrome.runtime.sendMessage({
      action: 'extractionStatus',
      state: state
    });
  } else if (request.action === 'batchExtracted') {
    chrome.runtime.sendMessage({
      action: 'batchExtracted',
      batchIndex: request.batchIndex,
      isLastBatch: request.isLastBatch,
      data: request.data
    });
    // 新增：全部抓取最后一批时，发送 extractionComplete
    if (request.isLastBatch && request.template) {
      const templateId = request.template;
      const state = getTemplateState(templateId);
      state.isRunning = false;
      state.result = null; // 可根据需要合并所有批次数据
      state.error = null;
      chrome.runtime.sendMessage({
        action: 'extractionComplete',
        state: state
      });
    }
    return;
  }
});

// 数据提取函数
function extractData(template) {
  // 这里实现实际的数据提取逻辑
  // 返回提取的数据
  return new Promise((resolve, reject) => {
    try {
      // 这里调用您的数据提取逻辑
      const data = window.extractData(template);
      resolve(data);
    } catch (error) {
      reject(error);
    }
  });
} 